import CommentItem from './CommentItem';
import CoworkRichText from '../../../public/CoworkRichText';
import isFunction from 'lodash/isFunction';
import { Pagination } from 'antd';

class CommentList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      edit: false,
      replyId: '',
      pageNum: 1,
      pageSize: 5,
      replyName: '',
    };
  }
  render() {
    const { list, isCanAnonymous, canReply } = this.props;
    let { edit, pageNum, pageSize } = this.state,
      total = list.length;
    let showList = [];
    let endNum = pageNum * pageSize;
    if (endNum > total) {
      endNum = total;
    }
    for (let i = (pageNum - 1) * pageSize; i < endNum; i++) {
      showList.push(list[i]);
    }
    return (
      <div className="wea-cowork-comment">
        {showList.map((item, index) => (
          <CommentItem
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_CommentItem@01n1mf@${index}`}
            operate={this.props.operate}
            {...item}
            reply={this.reply}
            canReply={canReply}
          />
        ))}
        {total > pageSize && (
          <div className="small-page">
            <Pagination
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_Pagination@awj0dc`}
              size="small"
              total={total}
              pageSize={pageSize}
              onChange={this.changePage}
              current={pageNum}
            />
            <div className="clear-both" />
          </div>
        )}
        {edit && canReply && (
          <CoworkRichText
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_CoworkRichText@vse3cs`}
            hasSubmit={true}
            ref="richText"
            submit={this.submit}
            cancel={this.cancel}
            isCanAnonymous={isCanAnonymous}
            editType="comment"
            replyName={this.state.replyName}
          />
        )}
      </div>
    );
  }

  reply = (id, name) => {
    this.setState({
      edit: true,
      replyId: id,
      replyName: name,
    });
  };

  submit = (params, callback) => {
    let saveParams = { ...params, replyType: 'comment' };
    saveParams.topdiscussid = this.props.topdiscussid;
    saveParams.replayid = this.state.replyId;
    isFunction(this.props.submit) &&
      this.props.submit(saveParams, this.cancel(callback));
  };

  cancel = (callback) => {
    this.setState(
      {
        edit: false,
        replyId: '',
      },
      () => {
        this.refs.richText &&
          this.refs.richText.wrappedInstance &&
          this.refs.richText.wrappedInstance.clear();
      },
    );
    isFunction(callback) && callback();
  };

  changePage = (pageNum) => {
    this.setState({ pageNum });
  };
}

export default CommentList;
